const {exec} = require('../db/mysql')
const xss = require('xss')

const getList = (author = "", keyword = "") => {
  let sql  = `select 
  id,
  title,
  author,
  date_format(createtime, '%Y-%c-%d %H:%i:%s' ) as createtime
  from blogs where 1=1 and status=1
  `
  if(author){
    sql += ` and author like '%${author}%'`
  }
  if(keyword){
    sql += ` and title like '%${keyword}%'`
  }
  return exec(sql)
};
const getDetail = (id = "") => {
  const sql = `select * from blogs where id='${id}' and status=1`
  if(id){
    return exec(sql).then(res=>{
      if(res.length){
        return res[0]
      }else{
        return null
      }
    })
  }else{
    return new Promise(resolve=>resolve(null))
  }
};
const newBlog = (title,content,author) => {
  const sql = `insert into blogs (title,content,author) values ('${xss(title)}','${xss(content)}','${author}')`
  return exec(sql).then(insertData=>{
    return insertData.insertId
  })
};
const updateBlog = (title,content,author,id) => {
  const sql = `update blogs set title='${xss(title)}',content='${xss(content)}' where author='${author}' and id='${id}'`
  return exec(sql).then(updateData=>{
    return updateData.affectedRows
  })
};
const deleteBlog = (author,id) => {
  // const sql = `delete from blogs where author='${author}' and id='${id}'`
  // 逻辑删除
  const sql = `update blogs set status=0 where author='${author}' and id='${id}'`
  return exec(sql).then(delData=>{
    return delData.affectedRows
  })
};
module.exports = {
  getList,
  getDetail,
  newBlog,
  updateBlog,
  deleteBlog,
};
